#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   run.py
@Time    :   2020/09/27 15:20:19
@Author  :   fengzhilaoling 
@Version :   1.0
@Contact :   fengzhilaoling@163.com
'''
from flask import Flask
from flask_session import Session
from flask import request
from flask import make_response
from flask import render_template
from flask import url_for
from flask import redirect
from flask import session
from redis import Redis
from datetime import datetime
from datetime import timedelta
import uuid
import os


class config:
    SESSION_TYPE = 'redis'  # session存储到redis中
    host = '39.96.7.141'  # redis服务器地址
    port = 6379  # redis端口
    overdue_time = timedelta(days=7)  # 过期时间为7天
    SESSION_REDIS = Redis(host=host, port=port, db=0)
    SESSION_USE_SIGNER = True  # 是否加盐
    SECRET_KEY = os.urandom(24)  # 加的盐， 使用os.urandom(24)生成随机的盐
    SESSION_PERMANENT = True  # session是否长期有效，如果为False，关闭浏览器session失效
    PERMANENT_SESSION_LIFETIME = 60  # session的过期时间
    DEBUG = True


def check_status(func):
    def inner(*args, **kwargs):
        status = request.cookies.get('status')
        if status == '1':
            response = func(*args, **kwargs)
            return response
        else:
            return redirect(url_for('login'))
    return inner


app = Flask(__name__)
app.config.from_object(config)
Session(app)


@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    elif request.method == 'POST':
        user_name = request.form.get('user_name')
        password = request.form.get('password')
        if user_name == 'fengling' and password == 'tian':
            sessionid = str(uuid.uuid4())  # 生成UUID值
            session[sessionid] = user_name  # 设置session，将UUID作为key，用户名作为value
            response = render_template('index.html')  # 获取index页面
            response = make_response(response)   # 将index作为response对象返回
            # 设置返回页面的cookie值，将UUID作为value，sessionid为key
            response.set_cookie('sessionid', sessionid)
            response.set_cookie('status', '1')
            return response


@app.route('/home/')
@check_status
def home():
    result = request.cookies.get('sessionid')
    session_value = session.get(result, 'a')
    return session_value


if __name__ == '__main__':
    app.run()
